package com.tcs.job;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;

import com.tcs.model.porxypool.proxyPoolBean;
import com.tcs.model.porxypool.RequestParamsBean;
import com.tcs.reptile.accept.Accept;
import com.tcs.reptile.accept.impl.PCAcceptImpl;
import com.tcs.util.constant.SystemConstants;
import com.tcs.util.spring.SpringConfigTool;

/**
 * job
 * @author wangbo
 */
public abstract class AbstractRequestJob implements IRequestJob {
	
	private final Logger logger = LoggerFactory.getLogger(AbstractRequestJob.class);
	
	protected ExecutorService executorService = null;
	
	protected proxyPoolBean proxyPoolBean = null;
	
	protected RequestParamsBean requestParamsBean;
	
	protected CountDownLatch countDownLatch = null;
	
	// 爬虫参数配置, 默认PC端参数
	protected Accept accept;
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDataMap jobDataMap = context.getMergedJobDataMap();
		proxyPoolBean = (proxyPoolBean) jobDataMap.get(SystemConstants.ProxyPool.PROXYPOOLMODEL);
		requestParamsBean = (RequestParamsBean) jobDataMap.get(SystemConstants.ProxyPool.REQUESTPARAMSBEAN);
		this.initParams();
		this.work();
	}
	
	@Override
	public void execute(Runnable runnable) {
		executorService.execute(runnable);
	}
	
	protected void initParams() {
		try {
			accept = (Accept) SpringConfigTool.getBean(PCAcceptImpl.class);
		} catch (BeansException e) {
			logger.error("接收对象未找到. 系统挂掉" , e);
			System.exit(1);
		}
		// 如果当前page页数量大于300,则改用缓存线程池,否则使用可重用无界队列线程池
		if (this.getForNum() > 300) {
			executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                    120L, TimeUnit.SECONDS,
                    new SynchronousQueue<Runnable>());
		} else {
			executorService = Executors.newFixedThreadPool(requestParamsBean.getThreadNum());
		}
		countDownLatch = new CountDownLatch(requestParamsBean.getThreadNum());
	}
	
	/**
	 * 页数<br>
	 * 如果page没有配置,默认为3000页
	 * @return {@link Integer} 
	 */
	protected Integer getForNum() {
		Integer page = requestParamsBean.getPage();
		if (page == 0) {
			page = 3000;
		} else {
			page = requestParamsBean.getPage();
		}
		return page;
	}
}